﻿using Business.DB.Interface;
using Business.DB.SqlServer;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MyReflecttion
{
    public class SimpleFactory
    {
        /// <summary>
        /// 提供一个返回IDBHelper的方法 
        /// 1、完全断开了对于普通类的依赖
        /// 2、配置文件的修改，不需要停止项目运行
        /// 3、反射+配置文件+简单工厂===程序的可配置化， 可以扩展化~
        /// </summary>
        /// <returns></returns>
        public static IDBHelper CreateInstance()
        {
            #region 利用配置文件 减少依赖
            string ReflictionConfig = CustomConfigManager.GetConfig("ReflictionConfig");
            string[] strings = ReflictionConfig.Split(',');
            string dllName = strings[1];
            string typeName = strings[0]; 
            #endregion


            Assembly assembly = Assembly.LoadFrom(dllName); ////不用带上dll的后缀,在当前执行目录下面去读取  .NET Framework下是可行的；.net8.0 测试不行

            
            Type type = assembly.GetType(typeName); //写入全名称
            object? oInstance = Activator.CreateInstance(type);            

            //类型的转换   这种方法最佳。
            IDBHelper dBHelper = oInstance as IDBHelper;
            
            return dBHelper;
        }
    }

    public static class CustomConfigManager
    {
        //Core 读取配置文件：appsettings
        //1.Microsoft.Extensions.Configuration；
        //2.Microsoft.Extensions.Configuration.Json 
        public static string GetConfig(string key)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");  //默认读取  当前运行目录
            IConfigurationRoot configuration = builder.Build();
            string configValue = configuration.GetSection(key).Value;
            return configValue;
        }
    }
}
